package com.nuc.seckill.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.nuc.seckill.base.BaseRequest;
import com.nuc.seckill.base.BaseResponse;
import com.nuc.seckill.base.UserReq;
import com.nuc.seckill.base.UserResp;
import com.nuc.seckill.entity.CommonWebUser;
import com.nuc.seckill.exception.ErrorMessage;
import com.nuc.seckill.model.SeckillUser;
import com.nuc.seckill.service.UserService;
import com.nuc.seckill.utils.RedisUtil;
import com.nuc.seckill.utils.WebUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.UUID;

/**
 * @author spider
 */
@RestController
@RequestMapping(value = "/user")
@Slf4j
public class UserController {
    private final String USER_EMAIL_CODE_BEFORE = "u:e:c:b:";
    @Value("${spring.mail.username}")
    private String from;
    @Resource
    private JavaMailSender javaMailSender;
    @Resource
    private UserService userService;
    @Resource
    private RedisUtil redisUtil;

    /**
     * 发送邮箱验证码
     * 验证手机号是否为注册用户手机号
     * 非注册报错， 否则生成随机验证码，然后调用第三方接口给用户发送验证码
     * 将随机数保存在redis，给接口调用方返回成功信号
     *
     * @param req 请求参数
     * @return com.nuc.seckill.base.BaseResponse<java.lang.Boolean>
     * @author 石一歌
     * @date 2022/8/4 23:01
     */
    @PostMapping("/getEmailSmsCode")
    public BaseResponse<?> getEmailSmsCode(@Valid @RequestBody BaseRequest<UserReq.BaseUserInfo> req) {
        String email = req.getData().getEmail();
        SeckillUser seckillUser = userService.findByEmail(email);
        //先判断用户存在
        //接下来调用第三方http接口发送短信验证码，通过验证码存储在redis中，
        if (seckillUser != null) {
            //邮箱验证码
            String randomCode = RandomUtil.randomNumbers(6);
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setTo(email);
            message.setSentDate(DateUtil.date());
            message.setSubject("【石一歌】登录邮箱验证");
            message.setText("您本次登录的验证码是：" + randomCode + "，有效期30分钟。请妥善保管，切勿泄露");
            javaMailSender.send(message);
            redisUtil.set(USER_EMAIL_CODE_BEFORE + email, randomCode, 60 * 30);
            return BaseResponse.ok(true);
        } else {
            return BaseResponse.error(ErrorMessage.PARAM_ERROR);
        }
    }

    /**
     * 用户邮箱登录
     * 先验证用户输入的验证码是否正确
     * 验证成功后删除redis中的验证码
     * 生成登录用的token，下发token
     *
     * @param req 请求
     * @return com.nuc.seckill.base.BaseResponse<?>
     * @author 石一歌
     * @date 2022/8/5 13:49
     */
    @PostMapping("/userEmailLogin")
    public BaseResponse<?> userEmailLogin(@Valid @RequestBody BaseRequest<UserReq.LoginUserInfo> req) {
        //验证邮箱验证码
        UserReq.LoginUserInfo loginInfo = req.getData();
        Object existObj = redisUtil.get(USER_EMAIL_CODE_BEFORE + loginInfo.getEmail());
        if (existObj == null || !existObj.toString().equals(loginInfo.getSmsCode())) {
            return BaseResponse.error(ErrorMessage.SMSCODE_ERROR);
        } else {
            redisUtil.del(USER_EMAIL_CODE_BEFORE + loginInfo.getEmail());
            SeckillUser seckillUser = userService.findByEmail(loginInfo.getEmail());
            CommonWebUser commonWebUser = new CommonWebUser();
            BeanUtils.copyProperties(seckillUser, commonWebUser);
            String token = UUID.randomUUID().toString().replaceAll("-", "");
            //设置token超时时间为1个月，实际根据需求确定
            redisUtil.set(token, JSON.toJSONString(commonWebUser), 60 * 60 * 24 * 30);
            UserResp.BaseUserResp resp = new UserResp.BaseUserResp();
            resp.setToken(token);
            return BaseResponse.ok(resp);
        }
    }

    @GetMapping("/checkUserToken")
    public void checkUserToken() {
        CommonWebUser commonWebUser = WebUserUtil.getLoginUser();
        log.info(JSON.toJSONString(commonWebUser));
    }
}
